﻿/*
 * Twipler - Twitter Web Client with features.
 *  
 *  Copyright (C) 2009, 2010. Ian Quigley
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details. 
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */


using System;
using System.Linq;
using System.Threading;
using System.Web.UI;
using Dimebrain.TweetSharp.Fluent;
using Twipler.App;
using Twipler.App.Session;
using Twipler.WebApp;
using Dimebrain.TweetSharp.Model;
using Twipler.Data.Entity.Twipler;
using Twipler.Data.Access;
using NHibernate.Criterion;
using System.Collections.Generic;
using Twipler.Xtensions;

public partial class OAuthLogin : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Current.SessionTrack.ViewingPage("Default.aspx");
    }

    protected void tickNow_Update(object sender, EventArgs e)
    {
        tickNow.Enabled = false;
        
        // Fancy OAuth login
        if (Request["oauth_token"] != null)
        {
            lock (this)
            {
                Current.SessionTrack.ApiCaller.AuthenticateResponse(Request["oauth_token"]);
                Visitors.Login(Current.SessionTrack.ApiCaller.Request(t => t.Account().VerifyCredentials(), false));
            }
        }
        
        // experimental twipler login
        else if (Request["twip"] != null)
        {
            string[] credentials;
            lock (this)
            {
                credentials = Current.SessionTrack.Credentials;
                Current.SessionTrack.Credentials = null;
            }

            if ((credentials != null) && (credentials.Length == 2))
            {
            	Visitor find = Factory.Visitor.GetByCriteria(Restrictions.Eq("ScreenName", credentials[0])).FirstOrDefault();
                if (find != null)
                {
					Current.SessionTrack.OAuthToken = (new OAuthTokenInvalid()).Decrypt(find.OAuthToken, credentials[1]);
                	bool isInvalid = Current.SessionTrack.OAuthToken is OAuthTokenInvalid;

					lock(this.GetType())
					{
						if (isInvalid)
						{
							Thread.Sleep(1000);
							Current.Log.Warn("Twipler login failed for user: " + credentials[0]);
						}
					}

					Current.Log.Debug("Twipler login " + credentials[0] + " " + credentials[1]);

					if (!isInvalid)
						Visitors.Login(Current.SessionTrack.ApiCaller.Request(t => t.Account().VerifyCredentials(), false));
                }
            }

			if (Current.Visitor.IsAnonymous)
				Response.Redirect("default.aspx?msg=ce");
            
        }
        // Boring old mechanism
        else if (Request["basic"] != null)
        {
            int login;
            lock (this)
            {
                login = Visitors.Login(Current.SessionTrack.ApiCaller.Request(t => t.Account().VerifyCredentials(), false));
            }

            if (login == -1)
                Response.Redirect("default.aspx?msg=ce");
        }

		// Kick off background processing
		if ((Current.Visitor != null) && (!Current.Visitor.IsAnonymous))
		{
			IInnerSession innerSession = Current.SessionTrack;
			Twipler.Accounts.TwitterUser user = Current.Visitor.TwitterUser;

			ThreadStart work = () => user.BackgroundProcess(innerSession);
			Thread thread = new Thread(work);
			thread.Start();
		}

    	Response.Redirect("default.aspx");
    }
}
